package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 山顶洞人郑某
 * @className UserServiceImpl.java
 * @date 2024 02 07
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获取用户的openid
       String opendId = getOpenid(userLoginDTO.getCode());
        if (opendId == null){
            //如果没有获取到，抛出异常
            throw  new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //查询数据库中是否有当前用户信息
        User user = userMapper.getByOpenId(opendId);
        //将openid作为用户的标识符存入数据库
        if (user == null){
            user = User.builder()
                    .createTime(LocalDateTime.now())
                    .openid(opendId)
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 获取用户的微信openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        Map<String ,String > map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //通过Client发向微信服务器发送请求获取用户信息
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //将用户信息转换为JSON格式
        JSONObject jsonObject = JSON.parseObject(json);
        //获取用户的openid
        String opendId = jsonObject.getString("openid");
        return opendId;
    }
}
